package com.io.commonlib.helper

import android.util.Base64
import java.nio.charset.Charset
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

object EncryptHelper {

    /**
     * @param text      要签名的文本
     * @param secretKey 阿里云MQ secretKey
     * @return 加密后的字符串
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     */
    @Throws(InvalidKeyException::class, NoSuchAlgorithmException::class)
    fun encryptSHA(text: String, secretKey: String): String {
        val charset = Charset.forName("UTF-8")
        val algorithm = "HmacSHA1"
        val mac = Mac.getInstance(algorithm)
        mac.init(SecretKeySpec(secretKey.toByteArray(charset), algorithm))
        val bytes = mac.doFinal(text.toByteArray(charset))
        // android的base64编码注意换行符情况, 使用NO_WRAP
        return String(Base64.encode(bytes, Base64.NO_WRAP), charset)
    }

    /**
     * @param text      要签名的文本
     * @param secretKey 阿里云MQ secretKey
     * @return 加密后的字符串
     */
    @Throws(InvalidKeyException::class, NoSuchAlgorithmException::class)
    fun encryptSHABase64(text: String, secretKey: String): String {
        val signingKey = SecretKeySpec(secretKey.toByteArray(Charsets.UTF_8), "HmacSHA1")
        val mac = Mac.getInstance("HmacSHA1")
        mac.init(signingKey)
        val rawHmac = mac.doFinal(text.toByteArray(Charsets.UTF_8))
        return Base64.encodeToString(rawHmac, Base64.DEFAULT)
    }

}